﻿using DBMC_Core;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace DBMC
{
    /// <summary>
    /// Init.xaml 的交互逻辑
    /// </summary>
    public partial class Init : Window
    {
        private bool isDragging;
        private Point startPoint;
        public ObservableCollection<UserInfo> Users { get; set; }
        public Minecraft minecraft = new Minecraft();
        LauncherCore launcherCore = new LauncherCore();
        RootObject dbmcData;
        public bool IsMain;
        private bool JavaPathExists
        {
            get
            {

                if (launcherCore.ConfigFileExists)
                {
                    string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                    dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                }
                return dbmcData.JavaPath != "";
            }
        }

        public Init(bool main = true)
        {
            InitializeComponent();
            Loaded += async (sender, e) => await InitLoading(main);
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Minimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private async void StartMain(bool main)
        {
            await Task.Delay(1000);
            if (main)
            {
                MainWindow Window = new MainWindow();
                Window.Show();
                Close();
                LauncherCore.WriteLog("启动器核心：初始化完毕 - 初始化页面已关闭");
            }
            else
            {
                DialogResult = true;
                Close();
            }
        }

        private async Task InitLoading(bool main)
        {
            LauncherCore.WriteLog("启动器：初始化中...");
            IsMain = main;
            LoadingTips.Text = "Java：寻找中...";
            await Task.Delay(3000);
            if (!minecraft.IsJava)
            {
                if (!minecraft.CheckJavaVersion)
                {
                    if (!JavaPathExists)
                    {
                        await Dispatcher.InvokeAsync(() =>
                        {
                            LoadingTips.Text = "Java：未找到Java路径";
                            LauncherCore.WriteLog("启动器核心：初始化 | Java - 未找到Java路径");
                            LoadingIcon.Visibility = Visibility.Hidden;
                            CloseIcon.Visibility = Visibility.Visible;
                        });
                        await Task.Delay(1000);
                        await Dispatcher.InvokeAsync(() =>
                        {
                            Loading.Visibility = Visibility.Hidden;
                            JavaOption.Visibility = Visibility.Visible;
                            LauncherCore.WriteLog("启动器核心：初始化 | Java - 已启用手动Java路径页面");
                        });

                        return;
                    }
                    else
                    {
                        await Dispatcher.InvokeAsync(() =>
                        {
                            LoadingTips.Text = "Java：找到自定义位置";
                            LauncherCore.WriteLog("启动器核心：初始化 | Java - 找到自定义位置");
                            LoadingIcon.Visibility = Visibility.Hidden;
                            CheckIcon.Visibility = Visibility.Visible;
                        });
                        SetInit(2);
                        StartMain(main);
                    }
                }
                else
                {
                    await Dispatcher.InvokeAsync(() =>
                    {
                        LoadingTips.Text = "Java：找到系统位置";
                        LauncherCore.WriteLog("启动器核心：初始化 | Java - 找到系统位置");
                        LoadingIcon.Visibility = Visibility.Hidden;
                        CheckIcon.Visibility = Visibility.Visible;
                    });
                    SetInit(1);
                    StartMain(main);
                }
            }
            else
            {
                await Dispatcher.InvokeAsync(() =>
                {
                    LoadingTips.Text = "Java：找到默认位置";
                    LauncherCore.WriteLog("启动器核心：初始化 | Java - 找到默认位置");
                    LoadingIcon.Visibility = Visibility.Hidden;
                    CheckIcon.Visibility = Visibility.Visible;
                });
                SetInit(0);
                StartMain(main);
            }
        }

        private void SetJavaPath_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog("启动器核心：初始化 | Java设置页面 - 用户点击了选择Java");
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Java.exe|java.exe",
                Title = "选择 Java.exe"
            };

            bool? result = openFileDialog.ShowDialog();

            if (result == true)
            {
                string fileName = openFileDialog.FileName;
                if (!minecraft.CheckUseJavaVersion(fileName))
                {
                    LauncherCore.WriteLog("启动器核心：初始化 | Java设置页面 - 用户选择的Java版本不对");
                    MessageBox.Show("Java版本不对", null, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                JavaPath.Text = fileName;
                SetInit(2, fileName);
                LoadingTips.Text = "Java：设置成功";
                LauncherCore.WriteLog("启动器核心：初始化 | Java设置页面 - Java设置成功");
                LoadingIcon.Visibility = Visibility.Hidden;
                CloseIcon.Visibility = Visibility.Visible;
                Loading.Visibility = Visibility.Hidden;
                JavaOption.Visibility = Visibility.Visible;
                StartMain(IsMain);
            }
        }

        private void SetInit(int type, string javapath = "")
        {
            RootObject dbmcData;

            if (launcherCore.ConfigFileExists)
            {
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
            }
            else
            {
                dbmcData = new RootObject();
            }

            dbmcData.UseJavaOptions = type;
            if (type == 2)
            {
                dbmcData.JavaPath = javapath;
            }
            if (dbmcData?.Account == null)
            {
                Users = new ObservableCollection<UserInfo>();
                UserInfo danbai = new UserInfo { Name = "Y_DanBai", UUID = "6d93735b4fa54783945bcdc74160d580", Type = "local", Access_Token = "ebe43614a37b571d76fe5e64f30720cd", Isfixed = Visibility.Hidden, Time = launcherCore.GenerateTimeStamp };
                UserInfo mingming = new UserInfo { Name = "M_MingMing", UUID = "41bc3fe071014cd1b198e6f17cd56148", Type = "local", Access_Token = "1b94936e12e01a41d1925990898311c4", Isfixed = Visibility.Hidden, Time = launcherCore.GenerateTimeStamp };
                UserInfo huahua = new UserInfo { Name = "HuaHua2333", UUID = "4f4d22ff3124470697b446443baa22af", Type = "local", Access_Token = "1b94936e1ebe436141925990898311c4", Isfixed = Visibility.Hidden, Time = launcherCore.GenerateTimeStamp };
                Users.Add(danbai);
                Users.Add(mingming);
                Users.Add(huahua);
                dbmcData.Account = new ObservableCollection<UserInfo>(Users);
            }
            else
            {
                Users = new ObservableCollection<UserInfo>(dbmcData.Account);
            }
            MemoryMetrics.GetMemoryStatus(out _, out int availableMemory);
            LauncherCore.WriteLog("启动器核心：初始化 - 自动分配内存");
            dbmcData.UseMemory = availableMemory;
            dbmcData.StartTools = true;
            dbmcData.StartTopmost = true;
            dbmcData.GameTips = true;

            string updatedJsonData = JsonConvert.SerializeObject(dbmcData, Formatting.Indented);
            File.WriteAllText(launcherCore.ConfigFile, updatedJsonData);
            File.SetAttributes(launcherCore.ConfigFile, FileAttributes.Hidden);
            LauncherCore.WriteLog("启动器核心：初始化 - 配置文件已生成，正在关闭初始化页面，打开主页面中...");
        }
    }
}